<template>
  <el-dialog v-model="dialogVisible" title="选择用户" width="60%">
    <ProTable
      ref="proTable"
      title="授权用户列表"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :toolButton="false"
      rowKey="userId"
      height="260"
    >
    </ProTable>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addAuthUserBatch(proTable?.selectedListIds)" :disabled="!proTable?.isSelected"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="RoleAllowAuthUserDialog">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
// import { CirclePlus, CircleClose, Close } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { Role } from "@/api/interface/systemRole";
import { getRoleAllowAuthUserApi, addRoleAuthUserBatchApi } from "@/api/modules/role";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const dialogVisible = ref(false);

interface DialogProps {
  roleId: number;
  getTableList?: () => void;
}

const dialogProps = ref<DialogProps>({
  roleId: 0
});

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  dialogProps.value = params;
  initParam.roleId = params.roleId;
  // 请求接口
  proTable.value?.getTableList();
  // 清除历史用户选择
  proTable.value?.clearSelection();
  // 显示弹窗
  dialogVisible.value = true;
};

defineExpose({
  acceptParams
});

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  roleId: dialogProps.value.roleId
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.rows,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  return getRoleAllowAuthUserApi(params);
};

// 表格配置项
const columns: ColumnProps<Role.RoleAuthUserRes>[] = [
  { type: "selection", fixed: "left" },
  {
    prop: "userId",
    label: "用户编号"
  },
  {
    prop: "account",
    label: "用户账号",
    search: { el: "input" }
  },

  {
    prop: "nickName",
    label: "用户昵称"
  },
  {
    prop: "email",
    label: "用户邮箱"
  },
  {
    prop: "phoneNumber",
    label: "手机号码",
    search: { el: "input" }
  },
  {
    prop: "status",
    label: "状态",
    render: scope => {
      return (
        <>
          <el-tag type={scope.row.status == 1 ? "success" : "danger"}>{scope.row.status == 1 ? "启用" : "禁用"}</el-tag>
        </>
      );
    }
  },
  {
    prop: "createTime",
    label: "创建时间"
  }
];

// 批量添加授权用户
const addAuthUserBatch = (userIds: string[] | undefined) => {
  if (userIds == undefined || userIds.length < 1) {
    ElMessage({
      type: "error",
      message: `请选择需要添加的用户!`
    });
    return;
  }

  dialogVisible.value = false;

  // 批量添加授权用户
  const userIdNews: number[] = userIds.map(Number);
  const addRoleAuthUserRe: Role.RoleAuthUserAddBatchReq = {
    roleId: dialogProps.value.roleId,
    userIds: userIdNews
  };
  addRoleAuthUserBatchApi(addRoleAuthUserRe).then(res => {
    if (res.isSuccessful) {
      ElMessage({
        type: "success",
        message: `授权用户添加成功!`
      });
    } else {
      ElMessage({
        type: "error",
        message: `${res.message}`
      });
    }

    dialogProps.value.getTableList!();
  });
};
</script>
